/**
 * Copyright (c) 2015-2016, Michael Yang 杨福海 (fuhai999@gmail.com).
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.fxhy.base;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.fxhy.utils.InstanceUtil;
import com.github.pagehelper.Page;

public class JBaseController {
	

	/** 设置成功响应代码 */
	protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap) {
		return setSuccessModelMap(modelMap, null);
	}

	/** 设置成功响应代码 */
	protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap, Object data) {
		return setModelMap(modelMap, HttpCode.OK, data);
	}

	/** 设置响应代码 */
	protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code) {
		return setModelMap(modelMap, code, null);
	}

	/** 设置响应代码 */
	protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code, Object data) {
		Map<String, Object> map = InstanceUtil.newLinkedHashMap();
		map.putAll(modelMap);
		modelMap.clear();
		for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
			String key = iterator.next();
			if (!key.startsWith("org.springframework.validation.BindingResult") && !key.equals("void")) {
				modelMap.put(key, map.get(key));
			}
		}
		if (data != null) {
			if (data instanceof Page) {
				Page<?> page = (Page<?>) data;
				modelMap.put("data", page.getResult());
				modelMap.put("recordsTotal", page.getResult().size());
				modelMap.put("total", page.getTotal());
				modelMap.put("current", page.getPageNum());
				modelMap.put("size", page.getPageSize());
				modelMap.put("pages", page.getPages());
			} else {
				modelMap.put("data", data);
			}
		}
		modelMap.put("httpCode", code.value());
		modelMap.put("msg", code.msg());
		modelMap.put("timestamp", System.currentTimeMillis());
		return ResponseEntity.ok(modelMap);
	}
	
	
	
	
	/** 设置响应代码 */
	protected ResponseEntity<ModelMap> setModelMapMsg(ModelMap modelMap, HttpCode code,String msg) {
		return setModelMapMsg(modelMap, code, msg,null);
	}

	/** 设置响应代码 */
	protected ResponseEntity<ModelMap> setModelMapMsg(ModelMap modelMap, HttpCode code,String msg,Object data) {
		Map<String, Object> map = InstanceUtil.newLinkedHashMap();
		map.putAll(modelMap);
		modelMap.clear();
		for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
			String key = iterator.next();
			if (!key.startsWith("org.springframework.validation.BindingResult") && !key.equals("void")) {
				modelMap.put(key, map.get(key));
			}
		}
		if (data != null) {
			if (data instanceof Page) {
				Page<?> page = (Page<?>) data;
				modelMap.put("data", page.getResult());
				modelMap.put("recordsTotal", page.getResult().size());
				modelMap.put("total", page.getTotal());
				modelMap.put("current", page.getPageNum());
				modelMap.put("size", page.getPageSize());
				modelMap.put("pages", page.getPages());;
			} else {
				modelMap.put("data", data);
			}
		}
		modelMap.put("httpCode", code.value());
		modelMap.put("msg", msg);
		modelMap.put("timestamp", System.currentTimeMillis());
		return ResponseEntity.ok(modelMap);
	}

	/** 异常处理 */
	@ExceptionHandler(Exception.class)
	public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex)
			throws Exception {
//		ModelMap modelMap = new ModelMap();
//		if (ex instanceof BaseException) {
//			((BaseException) ex).handler(modelMap);
//		} else if (ex instanceof IllegalArgumentException) {
//			new IllegalParameterException(ex.getMessage()).handler(modelMap);
//		} else if (ex instanceof UnauthorizedException) {
//			modelMap.put("httpCode", HttpCode.FORBIDDEN.value());
//			modelMap.put("msg", StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.FORBIDDEN.msg()));
//		} else {
//			modelMap.put("httpCode", HttpCode.INTERNAL_SERVER_ERROR.value());
//			String msg = StringUtils.defaultIfBlank(ex.getMessage(), HttpCode.INTERNAL_SERVER_ERROR.msg());
//			//modelMap.put("msg", msg.length() > 100 ? "系统走神了,请稍候再试." : msg);
//			modelMap.put("msg", "system error: " + msg);
//		}
//		response.setContentType("application/json;charset=UTF-8");
//		modelMap.put("timestamp", System.currentTimeMillis());
//		byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);
//		response.getOutputStream().write(bytes);
	}
}
